package com.gmail.bloim.serg.acmbuilder;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * User: Администратор
 * Date: 27.04.13
 * Time: 15:32
 */
public class SimpleConfigurableBuilder {

    private final BuildConfiguration configuration;
    private File dest;
    private Collection<File> sources = new ArrayList<File>();

    public SimpleConfigurableBuilder(BuildConfiguration config) {
        this.configuration = config;
        init();
    }

    private void init() {
        dest = new File(configuration.getDestination());
        String[] exts = {"java"};
        for (SourceDir sdir : configuration.getDirSources()) {
            Collection<File> files = FileUtils.listFiles(new File(sdir.getPath()), exts, false);
            sources.addAll(files);
        }
        for (SourceFile sfile : configuration.getFileSources()) {
            sources.add(new File(sfile.getPath()));
        }
    }

    public void build() throws IOException {
        ArrayList<JavaFile> javaFiles = new ArrayList<JavaFile>(sources.size());
        for (File source : sources) {
            JavaFile jfile = new JavaFile(source);
            javaFiles.add(jfile);
            jfile.parse();
        }
        JavaMerger merger = new JavaMerger();
        String merge = merger.merge(javaFiles);
        FileUtils.writeStringToFile(dest, merge);
    }
}
